package com.tanhua.houtai.server.service.impl;

import com.tanhua.domain.db.SoulTest;
import com.tanhua.domain.mongo.SoundTime;
import com.tanhua.dubbo.api.SoulTestApi;
import com.tanhua.houtai.server.utils.PayUtils;
import com.tanhua.houtai.server.domain.ResultInfo;
import org.apache.dubbo.config.annotation.Reference;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class PayServer {
    @Reference
    private SoulTestApi soulTestApi;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;
    public String getUrl(String uuid,String userId){
        redisTemplate.opsForValue().set("Order_"+uuid,userId);
        String order = PayUtils.createOrder(uuid, 1);
        return order;
    }

    public ResultInfo checkPay(Map<String, String> params) {
        //获取微信返回的订单号
        String out_trade_no = params.get("out_trade_no");
        System.out.println("订单号"+out_trade_no);
        //获取返回的支付状态
        String result_code = params.get("result_code");

        //如果支付成功
        if("SUCCESS".equals(result_code)){
            String userId = redisTemplate.opsForValue().get("Order_"+out_trade_no);
            //查看是否是会员是会员则延长时间，不是会员则改变状态
            SoundTime soundTime = soulTestApi.selectSoundTimeById(userId);
            if(soundTime.getAd()==1){
                soulTestApi.updatePayByid(userId,1);
                Long expire = redisTemplate.getExpire("VIP_AD_" + userId);
                System.out.println("剩下多少时间"+expire);
                redisTemplate.delete("Order_" + out_trade_no);
                redisTemplate.delete("VIP_AD_" + userId);
                redisTemplate.opsForValue().setIfAbsent("VIP_AD_" + userId, "语音vip", 120+expire, TimeUnit.SECONDS);
            }else {
                soulTestApi.updatePayByid(userId,1);
                soulTestApi.updateAdByid(userId);
                redisTemplate.delete("Order_" + out_trade_no);
                redisTemplate.opsForValue().setIfAbsent("VIP_AD_" + userId, "语音vip", 120, TimeUnit.SECONDS);
            }
            return new ResultInfo(true,"修改成功");
        }
        return new ResultInfo(false,"修改失败");
    }
    public ResultInfo findstate(Map<String, String> params) {
        String userId = params.get("userId");
        SoundTime soundTime = soulTestApi.selectSoundTimeById(userId);
        if(1==soundTime.getPay()){
            soulTestApi.updatePayByid(userId,0);
            return new ResultInfo(true,"支付成功");
        }
        return new ResultInfo(false,"支付失败");
    }


}
